import { RouteObject, useRoutes } from 'react-router-dom';
import { isValidElement, ComponentType, Suspense } from 'react';
import Layout from './updateLayout.tsx';
import { LazyComponent } from './LazyComponent.tsx';
// 定义模块类型
type Module = {
  default?: ComponentType;
};
const modules: Record<string, Module> = import.meta.glob('../pages/**/*.tsx', {
  eager: true,
});
console.log(modules, 'modules');
const Login = lazy(() => import('../pages/Login/index.tsx'));

const routesArray: RouteObject[] = [
  {
    path: '/',
    element: <Layout />,
    children: [],
  },
  {
    path: '/Login',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <Login />
      </Suspense>
    ),
  },
];

for (const [key, module] of Object.entries(modules)) {
  const path = key
    .replace('../pages', '')
    .replace('/index.tsx', '')
    .replace('.tsx', '');

  // 检查模块是否有默认导出，并且是 React 组件
  if (
    module.default &&
    (isValidElement(module.default) || typeof module.default === 'function')
  ) {
    const Component = module.default as ComponentType;

    const route: RouteObject = {
      path: path === 'index' ? '/' : path,
      element: (
        <>
          <LazyComponent>
            <Component />
          </LazyComponent>
        </>
      ),
    };
    if (path !== '/Login') {
      routesArray[0].children?.push(route);
    }
  } else {
    console.warn(`Invalid component found at path: ${key}`);
  }
}

console.log(routesArray, 'routesArray');

const Router = () => {
  const routes = useRoutes(routesArray);
  return routes;
};

export default Router;
